package com.example.bookdemo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Slf4j
public class SafeUtil {
    public static String getString(String password){
        log.info("输入密码,进行加密");
        String salt = UUID.randomUUID().toString().replace("-","");
        try {
            String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
            return salt+secretString;
        }catch (UnsupportedEncodingException e) {
            log.error("密文转换格式错误");
            return null;
        }
    }

    public static Boolean inputString(String inputPassword,String sqlPassword){
        if(sqlPassword==null||sqlPassword.length()!=64){
            return false;
        }
        String salt = sqlPassword.substring(0,32);
        try {
            String secretString = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes("UTF-8"));
            return sqlPassword.equals(salt+secretString);
        }catch (UnsupportedEncodingException e) {
            log.error("密文转换格式错误");
            return false;
        }
    }
}
